<template>
  <el-form
    :label-position="labelPosition"
    label-width="auto"
    :model="form"
    style="max-width: 600px"
  >
    <el-form-item label="姓名" :label-position="itemLabelPosition">
      <el-input v-model="form.username" />
    </el-form-item>
    <el-form-item label="性别" :label-position="itemLabelPosition">
      <el-select v-model="form.sex" placeholder="请选择" style="width: 240px">
        <el-option label="男" value="男" />
        <el-option label="女" value="女" />
    </el-select>
    </el-form-item>
    <el-form-item label="年龄" :label-position="itemLabelPosition">
      <el-input-number v-model="form.age" />
    </el-form-item>
    
    <el-button type="primary" @click="saveOrUser">{{ title}}</el-button>
    <el-button @click="$router.go(-1)">取 消</el-button>
  </el-form>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'

import type { FormItemProps, FormProps} from 'element-plus'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { id } from 'element-plus/es/locales.mjs'

const labelPosition = ref<FormProps['labelPosition']>('right')
const itemLabelPosition = ref<FormItemProps['labelPosition']>('')

// const form = reactive({
//   username: '',
//   sex: '男',
//   age: 1,
//   flag:'add'
// })
const form =ref({
  username: '',
  sex: '男',
  age: 1,
  flag:'add'
})
//通过路由获取参数
const par = history.state.user
let title = '保存'

if(par){
   // 将json字符串转换为对象
   const person = JSON.parse(par)
   console.log('------------>>>',person);
   if(person.id){
     title = '修改'
   }
  //  form.username = person.username
  //  form.sex = person.sex
  //  form.age = person.age
  //  form.flag = 'edit'
  //Object.assign(form,person)
  form.value = person
  form.value.flag = 'edit'
}



//保存
const saveUser = () => {
  axios.post('/api/save.do', form).then(res => {
  ElMessage({
    message: '保存成功.',
    type: 'success',
  })
  })
}

const updateUser = () => {
  axios({
    method: 'post',
    url: '/api/save.do',
    data: form
  })
}
//保存或修改
const saveOrUser = () => {
  if(form.value.id){
    updateUser()
  }else{    
    saveUser()
  }
}
</script>
